<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <el-button style="float: right; padding: 3px 0" type="text" @click="() => this.isEdit = true"
        >编辑</el-button
      >
    </div>
    <el-form ref="book" :model="book" :rules="rules" label-width="80px">
      <el-form-item label="书籍名称" prop="name">
        <el-input v-model="book.name" :readonly="!isEdit"></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input v-model="book.author" :readonly="!isEdit"></el-input>
      </el-form-item>
      <el-form-item label="书籍图片">
        <el-upload
          action="#"
          list-type="picture-card"
          :file-list="book.photo"
          :on-change="handleChange"
          :disabled="!isEdit"
          :auto-upload="false"
        >
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{ file }">
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.url"
              alt=""
            />
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="书籍类别" prop="category">
        <el-checkbox-group v-model="book.category" :disabled="!isEdit">
          <el-checkbox label="小说" key="1"></el-checkbox>
          <el-checkbox label="儿童读物" key="2"></el-checkbox>
          <el-checkbox label="专业书" key="3"></el-checkbox>
          <el-checkbox label="工具书" key="4"></el-checkbox>
          <el-checkbox label="手册" key="5"></el-checkbox>
          <el-checkbox label="剧本" key="6"></el-checkbox>
          <el-checkbox label="摄影绘画集" key="7"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="价格" prop="price" required>
        <el-input v-model="book.price" type="number" :readonly="!isEdit">
          <template slot="prepend">￥</template>
        </el-input>
      </el-form-item>
      <el-form-item label="出版地">
        <div style="display: flex; justify-content: space-evenly">
          <el-select
            v-model="book.place.province"
            placeholder="请选择"
            @change="provinceChange"
            :disabled="!isEdit"
            filterable
          >
            <el-option
              v-for="item in province"
              :key="item._id"
              :label="item.name"
              :value="item.province"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="book.place.city"
            placeholder="请选择"
            @change="cityChange"
            :disabled="!isEdit"
            filterable
          >
            <el-option
              v-for="item in city"
              :key="item._id"
              :label="item.name"
              :value="item.city"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="book.place.county"
            placeholder="请选择"
            :disabled="!isEdit"
            filterable
          >
            <el-option
              v-for="item in county"
              :key="item._id"
              :label="item.name"
              :value="item.county"
            >
            </el-option>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="出版社">
        <el-input v-model="book.press" :readonly="!isEdit"></el-input>
      </el-form-item>
      <el-form-item label="出版时间">
        <el-date-picker
          v-model="book.date"
          :readonly="!isEdit"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :disabled="!isEdit"
          >立即创建</el-button
        >
        <el-button @click="() => this.$router.push('/list')">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
export default {
  mounted() {
    if (this.$route.path === "/book") {
      this.isEdit = true;
      this.isUpdate = false;
    }else{
      this.isEdit = false;
      this.isUpdate = true;
      let books = JSON.parse(window.sessionStorage.getItem('books'));
      let book = books.find(item => item.id.toString() === this.$route.params.bookId);
      let cities = JSON.parse(window.sessionStorage.getItem('cities'));
      this.city = cities.city.filter((item) => item.province === book.place.province);
      this.county = cities.county.filter(
        item => item.province === book.place.province && item.city === book.place.city
      );
      this.book = book;
    }
    if (!window.sessionStorage.getItem("cities")) {
      import("@/assets/cities.json").then((module) => {
        let data = Object.values(module);

        let cities = {};
        let province = [];
        let city = [];
        let county = [];

        data.forEach((item) => {
          if (item.city === "00") {
            province.push(item);
          } else if (item.county === "00") {
            city.push(item);
          } else {
            county.push(item);
          }
        });
        cities.province = province;
        cities.city = city;
        cities.county = county;

        window.sessionStorage.setItem("cities", JSON.stringify(cities));
        this.cities = cities;
        this.province = province;
      });
    } else {
      let cities = JSON.parse(window.sessionStorage.getItem("cities"));
      this.cities = cities;
      this.province = cities.province;
    }
  },
  data() {
    return {
      isEdit: true,
      isUpdate: false,
      book: {
        id: "",
        name: "",
        author: "",
        photo: [],
        category: [],
        price: "",
        place: { province: "", city: "", county: "" },
        press: "",
        date: "",
      },
      cities: { province: [], city: [], county: [] },
      province: [],
      city: [],
      county: [],
      rules: {
        name: [{ required: true, message: "请输入书名", trigger: "blur" }],
        author: [
          { required: true, message: "请输入作者", trigger: "blur" },
          { min: 2, max: 20, message: "长度2-20个字符", trigger: "blur" },
        ],
        category: [
          {
            type: "array",
            required: true,
            message: "至少选择一个分类",
            trigger: "change",
          },
        ],
      },
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
    };
  },
  methods: {
    getBase64(file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
          resolve(this.result);
        };
        reader.onerror = function () {
          reject("转换错误!");
        };
      });
    },
    onSubmit() {
      let books = window.sessionStorage.getItem("books");
      if(!this.isUpdate){
        this.book.id = new Date().getTime();
        if (books) {
          books = JSON.parse(books);
          books.push(this.book);
        } else {
          books = [this.book];
        }

        window.sessionStorage.setItem('length', (books.length - 1).toString());
      }else{
        books = JSON.parse(books);
        let index = books.findIndex(item => item.id.toString() === this.$route.params.bookId);
        if(index !== -1){
          books.splice(index, 1);
          books.push(this.book);
        }
      }
      
      window.sessionStorage.setItem("books", JSON.stringify(books));
      this.$router.push({ path: "/list" });
    },
    handleChange(file) {
      this.getBase64(file.raw).then((result) => {
        file.url = result;
        let photo = [...this.book.photo];
        photo.push(file);
        this.book.photo = photo;
      });
    },
    handleRemove(file) {
      let photo = [...this.book.photo];
      this.book.photo = photo.filter((item) => item.uid !== file.uid);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    provinceChange() {
      this.county = [];
      let provice = this.book.place.province;
      this.city = this.cities.city.filter((item) => item.province === provice);
      this.book.place.city = "";
      this.book.place.county = "";
    },
    cityChange() {
      let provice = this.book.place.province;
      let city = this.book.place.city;
      this.county = this.cities.county.filter(
        item => item.province === provice && item.city === city
      );
    },
  },
};
</script>

<style>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.el-upload-list__item > div{
  position: relative;
  height: 100%;
}
.el-upload-list__item > div > img{
  position: absolute;
  top: 50%;
  left: 50%;
  display: block;
  min-width: 100%;
  min-height: 100%;
  transform:translate(-50%,-50%);
}
</style>